import { formatCurrentDay, formatAttendanceStatus } from '../../../../utils/util'

const sliderWidth = 96 // 需要设置slider的宽度，用于计算中间位置

export default Behavior({
  data: {
    userInfo: '', // 学生信息
    weekArray: ['当前周', '第一周', '第二周', '第三周', '第四周', '第五周', '第六周', '第七周', '第八周', '第九周', '第十周', '第十一周', '第十二周', '第十三周', '第十四周', '第十五周', '第十六周', '第十七周', '第十八周', '第十九周', '第二十周'], // 第几周
    weekIndex: '0', // 第几周index

    tabs: [formatCurrentDay(), '周期课程', '考勤记录'], // tabs菜单
    activeIndex: 0, // tabs点击第几个（默认是从0开始）
    sliderOffset: 0, // tabs滑块的偏移量
    sliderLeft: 0, // tabs滑块离左边的距离
    tabsWidth: '33.33%', // tabs滑块的宽度

    bIsAuthorize: false, // 是否显示授权的课程
    authorize: { // 授权课程
      bgColor: '', // 背景颜色
      color: '', // 字体颜色
      bIsLight: false // 是否高亮
    },

    attendanceTime: [ // 考勤限时data
      { name: '5分钟', value: '5' },
      { name: '10分钟', value: '10' },
      { name: '15分钟', value: '15' },
      { name: '20分钟', value: '20' },
      { name: '25分钟', value: '25' }
    ],

    appMsg: { // 当数据为空时的组件
      type: '',
      show: false
    },
    refreshing: false
  },
  ready () {
    // 计算tabs菜单
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          userInfo: wx.getStorageSync('userInfo'), // 获取用户信息
          sliderLeft: (res.windowWidth / this.data.tabs.length - sliderWidth) / 300,
          sliderOffset: res.windowWidth / this.data.tabs.length * this.data.activeIndex
        })
      }
    })
  },
  methods: {
    /**
     * @see 接口--获取学生课程
     */
    getStuCourseInfo () {
      const { weekIndex } = this.data
      const request = {
        week: weekIndex === '0' ? '' : weekIndex
      }
      this.setData({
        appMsg: {
          type: 'loading',
          show: true
        }
      })
      wx.$API['schoolStudy/getStuCourseInfo'](request).then((result) => {
        const { data, currWeek, currDayTime } = result
        if (data.length) {
          formatAttendanceStatus(data)
          this.setData({
            courseData: data,
            currWeek,
            currDayTime,
            refreshing: false,
            tabs: [formatCurrentDay(currDayTime), '周期课程', '考勤记录'], // tabs菜单
            appMsg: {
              type: 'loading',
              show: false
            }
          })
          this.handleTabData(this.data.activeIndex)
        } else {
          this.setData({
            courseData: [],
            refreshing: false,
            appMsg: {
              type: 'none',
              show: true
            }
          })
          this.handleTabData(this.data.activeIndex)
        }
      }).catch((error) => {
        console.log(error)
        this.setData({
          courseData: [],
          viewCourseData: [],
          refreshing: false,
          appMsg: {
            type: 'err',
            show: true
          }
        })
      })
    },
    /**
     * @see 接口--获取授权课程列表
     */
    getAuthorizationCourse () {
      const { weekIndex } = this.data
      const request = {
        week: weekIndex === '0' ? '' : weekIndex
      }
      this.setData({
        appMsg: {
          type: 'loading',
          show: true
        }
      })
      wx.$API['schoolStudy/getAuthorizationCourse'](request).then((result) => {
        const { data, currWeek, currDayTime } = result
        if (data.length) {
          formatAttendanceStatus(data)
          this.setData({
            courseData: data,
            currWeek,
            currDayTime,
            refreshing: false,
            tabs: [formatCurrentDay(currDayTime), '周期课程'], // tabs菜单
            appMsg: {
              type: 'loading',
              show: false
            }
          })
          this.handleTabData(this.data.activeIndex)
        } else {
          this.setData({
            courseData: data,
            refreshing: false,
            tabs: [formatCurrentDay(currDayTime), '周期课程'], // tabs菜单
            appMsg: {
              type: 'none',
              show: true
            }
          })
          this.handleTabData(this.data.activeIndex)
        }
      }).catch((error) => {
        this.setData({
          courseData: [],
          viewCourseData: [],
          refreshing: false,
          appMsg: {
            type: 'err',
            show: true
          }
        })
      })
    },
    /**
     * @see 接口--获取学生考勤记录
     */
    getStudentAttendanceCount () {
      this.setData({
        appMsg: {
          type: 'loading',
          show: true
        }
      })
      wx.$API['schoolStudy/getStudentAttendanceCount']({}).then((result) => {
        const { data } = result
        if (data.length) {
          this.setData({
            stuAttendData: data,
            refreshing: false,
            appMsg: {
              type: 'loading',
              show: false
            }
          })
        } else {
          this.setData({
            stuAttendData: data,
            refreshing: false,
            appMsg: {
              type: 'none',
              show: true
            }
          })
          this.handleTabData(this.data.activeIndex, true)
        }
      }).catch((error) => {
        this.setData({
          stuAttendData: [],
          refreshing: false,
          appMsg: {
            type: 'err',
            show: true
          }
        })
      })
    },
    /**
     * @see 接口--学生签到
     */
    signIn (result) {
      const signInRequestQuery = () => {
        const { attendanceValue, form, attendanceWay } = this.data
        const baseRequest = {
          courseId: attendanceValue.courseId, // 课程id
          attendanceWay, // 考勤方式（1：定位，2：扫码，3：邀请码）
        }
        switch (attendanceWay) {
          case 1:
            return Object.assign(baseRequest, {
              latitude: form.latitude, // 纬度
              longitude: form.longitude, // 经度
              attendanceLocation: form.attendanceLocation // 考勤位置
            })
          case 2:
            return Object.assign(baseRequest, {
              qrCode: result.qrCode
            })
          case 3:
            return Object.assign(baseRequest, {

            })
          default:
            return baseRequest
        }
      }
      wx.showLoading({
        title: '正在提交...',
        mask: true
      })
      wx.$API['schoolStudy/signIn'](signInRequestQuery()).then((result) => {
        wx.hideLoading()
        this.setData({
          bIsLocationShow: false,
          bIsSuccessShow: true
        })
        this.getStuCourseInfo()
      }).catch((error) => {
        console.log(error)
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: error,
          showCancel: false
        })
      })
    },
    /**
     * @see 接口--老师开启考勤
     */
    startAttendance () {
      const { attendanceValue, currWeek, attendanceWay, form } = this.data
      let lateTimeLength
      if (form.lateInit !== '0' && form.lateInit !== '') {
        lateTimeLength = form.lateInit
      } else {
        lateTimeLength = form.timeValue
      }
      const request = {
        userId: attendanceValue.teacherId,
        name: attendanceValue.teacher, // 教师名称 √
        courseId: attendanceValue.courseId, // 课程id √
        dayTime: attendanceValue.dayTime, // 星期几 √
        lesson: attendanceValue.lesson, // 节数 √
        attendanceWay, // 考勤方式（1：定位，2：扫码，3：邀请码）
        courseName: attendanceValue.courseName, // 课程名称 √
        classRoom: attendanceValue.classRoom, // 教室 √
        week: currWeek, // 周数 √
        distance: form.distanceInit, // 异常距离 √
        latitude: form.latitude, // 经度 √
        longitude: form.longitude, // 纬度 √
        attendanceLocation: form.attendanceLocation, // 考勤位置 √
        attendanceLength: form.timeValue, // 考勤时长 √
        lateTimeLength // 迟到时长 √
      }
      wx.showLoading({
        title: '正在开启...',
        mask: true
      })
      wx.$API['schoolStudy/startAttendance'](request).then((result) => {
        wx.hideLoading()
        this.getAuthorizationCourse()
        this.setData({
          bIsAttendInfoShow: false,
          bIsSuccessShow: true
        })
      }).catch((error) => {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: error,
          showCancel: false
        })
      })
    },
    /**
     * @see 接口--老师结束考勤
     */
    endAttendance () {
      const { attendanceValue } = this.data
      const request = {
        courseId: attendanceValue.courseId // 课程id
      }
      wx.showLoading({
        title: '请稍后...',
        mask: true
      })
      wx.$API['schoolStudy/endAttendance'](request).then((result) => {
        wx.hideLoading()
        wx.showToast({
          title: result,
          icon: 'none'
        })
        this.getAuthorizationCourse()
      }).catch((error) => {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: error,
          showCancel: false
        })
      })
    },
  }
})